/*************************************************************************  
 *   This file is part of UBBMPSREADER.
 *
 *   UBBMPSREADER is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   UBBMPSREADER is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with UBBMPSREADER.  If not, see <http://www.gnu.org/licenses/>. 
 *************************************************************************/

package cs.ubbcluj.ro.mps.reader;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

import cs.ubbcluj.ro.mps.states.utils.CharConstants;

/**
 * Represents an MPS InputStream
 * 
 * @author avadas
 * @version 1.0
 */
public class MpsInputStream extends PushbackInputStream {
    /** The actual column */
    private int column = 0;

    /** The actual row */
    private int row = 1;

    /** The old column */
    private int oldColumn = 1;

    public MpsInputStream(final InputStream in) {
	super(in);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int read() throws IOException, NullPointerException {
	final int in = super.read();
	if (in == CharConstants.LF) {
	    this.oldColumn = getColumn();
	    setColumn(0);
	    setRow(getRow() + 1);
	} else {
	    setColumn(getColumn() + 1);
	}
	return in;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void unread(final int in) throws IOException, NullPointerException {

	if (in == CharConstants.LF) {
	    setColumn(this.oldColumn);
	    setRow(getRow() - 1);
	} else {
	    setColumn(getColumn() - 1);
	}
	super.unread(in);
    }

    /**
     * Sets the parsing column
     * 
     * @param column
     *            the curent column
     */
    private void setColumn(final int column) {
	this.column = column;
    }

    /**
     * Gets the parsing column
     * 
     * @return the current column
     */
    public int getColumn() {
	return this.column;
    }

    /**
     * Sets the parsing row
     * 
     * @param row
     *            the current row
     */
    private void setRow(final int row) {
	this.row = row;
    }

    /**
     * Gets the parsing row
     * 
     * @return the current row
     */
    public int getRow() {
	return this.row;
    }
}
